package com.saikei.demoapp.base

import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import com.saikei.demoapp.util.IntentStarter
import com.saikei.demoapp.util.IntentStarter.Companion.INTENT_FRAGMENT_NAME

class FragmentContainActivity : AppCompatActivity() {

    /** 容器 ID（可通过 getContainerId 自定义） */
    private fun getContainerId(): Int = android.R.id.content

    /** 设置 layout（可用于扩展 toolbar、状态栏等） */
    private fun getContainerView(): View {
        return FrameLayout(this).apply {
            id = getContainerId()
            layoutParams = ViewGroup.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT
            )
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(getContainerView())
        if (savedInstanceState == null) {
            loadFragmentFromIntent()
        }
    }

    private fun loadFragmentFromIntent() {
        try {
            val fragmentName = intent.getStringExtra(INTENT_FRAGMENT_NAME)
            val args = intent.extras
            if (fragmentName.isNullOrBlank()) {
                finish()
                return
            }
            val clazz = Class.forName(fragmentName).asSubclass(Fragment::class.java)
            val fragment = clazz.getDeclaredConstructor().newInstance()
            fragment.arguments = args
            supportFragmentManager.beginTransaction()
                .replace(getContainerId(), fragment, fragmentName)
                .commitAllowingStateLoss()
        } catch (e: Exception) {
            e.printStackTrace()
            finish()
        }
    }

    override fun finish() {
        super.finish()
        IntentStarter.create(this).finish()
    }
}
